from django.http import HttpResponse
from django.views.generic import FormView
from .forms import SignUp,SignIn
from django.urls import reverse_lazy
from .models import Users
from django.contrib.auth import authenticate,logout,login
from django.shortcuts import redirect

# Create your views here.

class LogUp(FormView):
    form_class = SignUp
    success_url = reverse_lazy('index')

    def form_valid(self, form):
        data = form.cleaned_data
        Users.objects.create_user(**data)
        return super().form_valid(form)
    def form_invalid(self, form):
        return HttpResponse('用户名已存在，请返回重新注册')
        # return super().form_valid(form)


class LogIn(FormView):
    form_class = SignIn

    def form_valid(self, form):
        data = form.cleaned_data
        user = authenticate(**data)
        if user is not None:
            login(self.request,user)
            return redirect(self.request.META['HTTP_REFERER'])
        else:
            return HttpResponse('账号或密码错误，请返回页面重新登录')

    def form_invalid(self, form):
        return redirect(self.request.META['HTTP_REFERER'])

    # def get_success_url(self):
    #     return redirect(self.request.META['HTTP_REFERER'])

def MyLogout(requset):
    logout(requset)
    return redirect(requset.META['HTTP_REFERER'])
